package com.sba.core.web.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sba.core.domain.User;
import com.sba.core.service.UserService;
import com.sba.core.util.HashUtil;

/**
 * 
 * @author feiliming
 *
 */
@Controller
@RequestMapping("${ssh.admin-path}/user")
public class UserController extends BaseController {

	private final UserService userService;
	
	@Value("${ssh.init-password}")
	protected String password;
	
	@Autowired
	public UserController(UserService userService){
		this.userService = userService;
	}
	
	@GetMapping
	public String index(){
		return adminThemePath + "/sys/user";
	}
	
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public @ResponseBody JSONObject getUsers(Long organizationId, Integer limit, Integer offset){
		if(limit == null){
			limit = Integer.MAX_VALUE;
		}
		if(offset == null){
			offset = 0;
		}
		
		Page<User> page;
		if(organizationId != null){
			page = userService.getUsers(organizationId, limit, offset);
		}else{
			page = userService.getUsers(limit, offset);
		}
		
		JSONObject obj = new JSONObject();
		obj.put("list", page.getContent());
		obj.put("total", page.getTotalElements());
		obj.put("totalPages", page.getTotalPages());
		return obj;
		
	}
	
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	public @ResponseBody JSONObject saveUser(User user){
		user.setPassword(HashUtil.md5(password));
		user.setCreateTime(new Date());
		JSONObject obj = new JSONObject();
		try {
			userService.saveOrUpdate(user);
			obj.put("success", true);
			obj.put("msg", "保存用户成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "保存用户失败！");
		}
		return obj;
	}
	
	@GetMapping("/get")
	public @ResponseBody User getById(Long id){
		User user = userService.getById(id);
		return user;
	}
	
	@RequestMapping(path = "/delete", method = RequestMethod.POST)
	public @ResponseBody JSONObject deleteUser(Long id){
		User user = userService.getById(id);
		user.setIsDelete(1);
		JSONObject obj = new JSONObject();
		try {
			userService.saveOrUpdate(user);
			obj.put("success", true);
			obj.put("msg", "删除用户成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "删除用户失败！");
		}
		return obj;
	}
	
}
